package com.example.servlet;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author feilin
 * 
 */
public class ImageServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		BufferedImage bi = new BufferedImage(78, 22, BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.getGraphics();
		Color c = new Color(200, 155, 255);
		g.setColor(c);
		g.fillRect(0, 0, 78, 22);
		
		char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
		Random r = new Random();
		int len = ch.length, index;
		StringBuffer sb = new StringBuffer();
		
		for (int i=0; i<5; i++) {
			index = r.nextInt(len);
			Color temp = new Color(r.nextInt(88), r.nextInt(168), r.nextInt(188));
			g.setColor(temp);
			g.drawString(ch[index]+"", (i*15)+3, 18);
			sb.append(ch[index]);
		}
		req.getSession().setAttribute("code", sb.toString());
		ImageIO.write(bi, "PNG", resp.getOutputStream());
	}

	
}
